import mongodbHandle from '../handle/mongodbHandle'
import sessionHandle from '../handle/sessionHandle'
import rankHandle from '../handle/rankHandle'
import routes from './route'
var ObjectId = require('mongodb').ObjectId;
var utility = require("utility");
import app from '../app'
import * as moment from 'moment'
import crossServiceBattleHandle from '../handle/crossServiceBattleHandle'

const jwt = require('jsonwebtoken');

import utils from '../serverCore/utils';
import redisHandle from 'src/handle/redisHandle';
// import arenaHandle from 'js/handle/arenaHandle';
import arenaHandle from 'core/handle/arenaHandle';
import arena from 'core/config/base/arena';
import fighterPartnerHandle from 'core/handle/fighterPartnerHandle';
import { PlayerModel } from 'core/model/playerModel';
import areaCsHandle from 'src/handle/areaCsHandle';
import { gameConfigHandle } from 'core/config/gameConfig';
import areaCsPlayHandle from 'core/handle/areaCsPlayHandle';

routes.setLogin('selectOpponent', [
], async (msg, session) => {
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
    if (myData.cheat) {
        return { err: 101 }
    }
    let myScore = myData.arenaScore || (100 * 100000000)
    let matchingScore = Math.floor(myScore * 0.85)
    if (matchingScore < 50) {
        matchingScore = 50
    }
    if (myScore < 100000000) {
        myScore = 100 * 100000000
    }
    let maxMatchingScore = myScore * 1.2
    let minMatchingScore = myScore * 0.75
    if (myScore <= 200 * 100000000) {
        maxMatchingScore = myScore * 1.1
        minMatchingScore = myScore * 0.6
    } else if (myScore > 200 * 100000000 && myScore <= 400 * 100000000) {
        maxMatchingScore = myScore * 1.1
        minMatchingScore = myScore * 0.65
    } else if (myScore > 400 * 100000000 && myScore <= 600 * 100000000) {
        maxMatchingScore = myScore * 1.15
        minMatchingScore = myScore * 0.7
    } else if (myScore > 600 * 100000000 && myScore <= 800 * 100000000) {
        maxMatchingScore = myScore * 1.2
        minMatchingScore = myScore * 0.7
    } else if (myScore > 800 * 100000000 && myScore <= 1000 * 100000000) {
        maxMatchingScore = myScore * 1.25
        minMatchingScore = myScore * 0.7
    } else if (myScore > 1000 * 100000000 && myScore <= 2000 * 100000000) {
        maxMatchingScore = 2000 * 100000000
        minMatchingScore = myScore * 0.7
    }

    maxMatchingScore = Math.floor(maxMatchingScore)
    minMatchingScore = Math.floor(minMatchingScore)
    let docs = await mongodbHandle.playerDao.findByPageAndSort({
        currentServerID: session.serverID,
        "cheat": {
            $ne: true
        },
        "arenaScore": {
            $gte: minMatchingScore,
            $lte: maxMatchingScore,
        },
    }, {
        "arenaScore": 1
    }, 0, 100)
    let players: any[] = []
    if (docs && docs.length > 0) {
        for (let i = 0; i < docs.length; i++) {
            let doc = docs[i]
            if (doc._id.toString() !== session.pID.toString()) {
                players.push(doc)
            }
        }
    }
    if (players.length == 0) {
        let docs = await mongodbHandle.playerDao.findByPageAndSort({
            currentServerID: session.serverID,
            "cheat": {
                $ne: true
            },
            "arenaScore": {
                $gte: myData.arenaScore || (100 * 100000000)
            },
        }, {
            "arenaScore": 1
        }, 0, 30)
        if (docs.length <= 1) {
            docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: session.serverID,
                "cheat": {
                    $ne: true
                },
                "arenaScore": {
                    $lte: myScore,
                },
            }, {
                "arenaScore": -1
            }, 0, 10)
        }
        if (docs && docs.length > 1) {
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                if (doc._id.toString() !== session.pID.toString()) {
                    players.push(doc)
                }
            }
        }
    }
    let opponents = [], my = false
    if (players.length > 0) {
        opponents = utils.getRandomArrayNoRepeat(4, players)
    } else {
        opponents = docs
    }
    opponents = opponents.map(item => {
        let team = []
        // if (item.arenaTeam && moment().valueOf() > (item.arenaTeamTime + 3 * 24 * 60 * 60 * 1000)) {

        // }else {
        //     for (let i = 0; i < 10; i++) {
        //         let partner = item.playerData.team.list[i]
        //         if (partner) {
        //             team.push(partner.tid)
        //         }
        //     }
        // }

        return {
            _id: item._id.toString(),
            id: item.id,
            name: item.name,
            totalPower: item.playerData.baseInfo.power,
            team: team,
            score: item.arenaScore
        }
    })
    return { err: 0, data: { opponents: opponents, myScore: myScore, my: my } }
})

routes.setLogin('getOpponent', [
    ['id', 'string']
], async (msg, session) => {
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(msg.id) })
    delete doc.playerData.bag
    delete doc.playerData.EquipmentBag
    delete doc.playerData.AbyssBag
    delete doc.playerData.PetBag
    delete doc.playerData.AbyssBag
    delete doc.playerData.RideBag
    delete doc.playerData.ItemInfo
    return { err: 0, data: doc }
})

routes.setLogin('getOpponentTeam', [
    ['id', 'string']
], async (msg, session) => {
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(msg.id) })
    if (doc.arenaTeam && moment().valueOf() < (doc.arenaTeamTime + 3 * 24 * 60 * 60 * 1000)) {
        return { err: 0, data: { team: doc.arenaTeam, _id: msg.id, id: msg.id, name: doc.name } }
    } else {
        let team = fighterPartnerHandle.initPartnerFighterTeam(new PlayerModel(doc.playerData))
        return { err: 0, data: { team, _id: msg.id, id: msg.id, name: doc.name } }
    }
})

routes.setLogin('getAreaList', [], async (msg, session, cb) => {
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
    let myScore = myData.arenaScore || 0

    let docs1 = await mongodbHandle.arenaDao.findByPageAndSort({
        pID1: session.pID
    }, {
        'time': -1
    }, 0, 20)
    let docs2 = await mongodbHandle.arenaDao.findByPageAndSort({
        pID2: session.pID
    }, {
        'time': -1
    }, 0, 20)
    let docs = docs1.concat(docs2)
    docs.sort((a1, a2) => {
        return a2.time - a1.time
    })
    docs = docs.slice(0, 20)
    docs.forEach(item => {

        delete item.player1
        delete item.player2
    })

    let arenaTimes = myData.arenaTimes
    if (myData.arenaTime !== moment().startOf('day').valueOf()) {
        arenaTimes = 0
    }
    return {
        err: 0, data: {
            data: docs, myScore: myScore, arenaTimes: arenaTimes, arenaPoint: myData.arenaPoint,
            arenaAutoTimes: myData.arenaAutoTimes || 0, arenaTeam: myData.arenaTeam,
            arenaTeamTime: myData.arenaTeamTime
        }
    }
})


routes.setLogin('getAreaBattleData', [
    ['id', 'string']
], async (msg, session, cb) => {
    let doc = await mongodbHandle.arenaDao.findOne({
        _id: ObjectId(msg.id)
    })
    return { err: 0, data: doc }
})

routes.setLogin('getProAreaBattleData', [
    ['id', 'string']
], async (msg, session, cb) => {
    let doc = await mongodbHandle.arenaDaoTest.findOne({
        _id: ObjectId(msg.id)
    })
    return { err: 0, data: doc }
})

routes.setLogin('getProCsAreaBattleData', [
    ['id', 'string']
], async (msg, session, cb) => {
    let doc = await mongodbHandle.csAarenaDaoTest.findOne({
        _id: ObjectId(msg.id)
    })
    return { err: 0, data: doc }
})

routes.setLogin('getCsAreaList', [], async (msg, session, cb) => {
    let myInfoData = await redisHandle.zscore(app.config.gameName + 'csBattleScore', session.pID)
    let myInfo = crossServiceBattleHandle.getPlayerInfo(myInfoData)
    // let csArenaPoint = myData.csArenaPoint || 0
    let docs = await mongodbHandle.csAarenaDao.findByPageAndSort({
        pID1: session.pID
    }, {
        'time': -1
    }, 0, 25)
    docs.forEach(item => {
        delete item.player1
        delete item.player2
    })
    return { err: 0, data: { data: docs, csArenaInfo: myInfo } }
})

routes.setLogin('getCsAreaBattleData', [
    ['id', 'string']
], async (msg, session, cb) => {
    let doc = await mongodbHandle.csAarenaDao.findOne({
        _id: ObjectId(msg.id)
    })
    return { err: 0, data: doc }
})


routes.setLogin('saveArenaData', [
    ['p2ID', 'string'],
    ['name1', 'string'],
    ['name2', 'string'],
    ['playerTeam1', 'string'],
    ['playerTeam2', 'string'],
    ['team1TID', 'array'],
    ['team2TID', 'array'],
    ['result', 'number'],
    ['version', 'string'],
    ['seed', 'number'],
    ['type', 'number', false]
], async (msg, session, cb) => {
    let { name1, name2, p2ID, playerTeam1, playerTeam2, result, version, seed, type, team1TID, team2TID } = msg
    let player1 = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
    let arenaTimes = player1.arenaTimes
    let arenaTime = player1.arenaTime
    if (player1.arenaTime !== moment().startOf('day').valueOf()) {
        arenaTimes = 0
        arenaTime = moment().startOf('day').valueOf()
    }
    if (arenaTimes >= 13) {
        return { err: 1 }
    }
    let player2 = await mongodbHandle.playerDao.findOne({ _id: ObjectId(p2ID) })
    let { player1Score, player2Score, addScore1, addScore2 } = arenaHandle.calcScore(player1.arenaScore, player2.arenaScore, result, moment().valueOf())

    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(session.pID),
    }, {
        $set: {
            arenaScore: player1Score,
            arenaTimes: arenaTimes + 1,
            arenaTime: arenaTime
        }
    })
    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(p2ID),
    }, {
        $set: {
            arenaScore: player2Score
        }
    })
    await mongodbHandle.arenaDao.newAndSave(name1, name2, session.pID, p2ID, playerTeam1, playerTeam2, team1TID, team2TID, Math.floor(addScore1), Math.floor(addScore2), result, seed, version, type)
    return { err: 0 }
    // if (count < 40) {
    //     let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
    //     let otherData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(p2ID) })
    //     // arenaAutoHandle.saveArenaData2(session.pID, p2ID, player1, player2, addScore1, addScore2, result, version, seed, point, myData, otherData)
    //     return { err: 0 }
    // } else {
    //     return { err: 0 }
    // }
})

routes.setLogin('getRank', [
    ['serverID', 'number'],
    ['pid', 'string'],
    ['phone', 'string'],
    ['type', 'string'],
], async (msg) => {
    let { serverID, pid, phone, type } = msg
    let rank = [], myRank
    if (type === 'power') {
        let rankData = rankHandle.getPowerRank(serverID, phone)
        myRank = rankHandle.getPowerRankByPID(serverID, pid, phone)
        if (rankData) {
            rank = rankData.slice(0, 150)
        }
    } else if (type === 'progress') {
        let rankData = rankHandle.getMapProgressRank(serverID, phone)
        myRank = await rankHandle.getMapProgressRankByPID(serverID, pid, phone)
        if (rankData) {
            rank = rankData.slice(0, 150)
        }
    } else if (type === 'arena') {
        let rankData = rankHandle.getArenaRank(serverID, phone)
        myRank = rankHandle.getArenaRankByPID(serverID, pid, phone)
        rank = []
        if (rankData) {
            rank = rankData.slice(0, 150)
        }
    } else if (type === 'abyss') {
        let rankData = rankHandle.getAbyssProgressRank(serverID, phone)
        myRank = await rankHandle.getAbyssProgressRankByPID(serverID, pid, phone)
        if (rankData) {
            rank = rankData.slice(0, 150)
        }
    }

    return {
        err: 0, data: {
            rankData: rank,
            myRank
        }
    }
})

routes.setNotLogin('rankList1', [
    ['page', 'number'],
    ['pageSize', 'number'],
    ['type', 'number'],
    ['serverID', 'number'],
    ['pID', 'string', false],
    ['phone', 'string', false],
], async (msg, session, cb) => {
    let {
        page,
        pageSize,
        type,
        serverID,
        pID,
        phone,
    } = msg
    let query: any = {}
    if (serverID) {
        let pDocs = await mongodbHandle.playerDao.find({ currentServerID: serverID })
        let pIDs = []
        for (let i = 0; i < pDocs.length; i++) {
            pIDs.push(pDocs[i].id)
        }
        query.pID = { $in: pIDs }
    }
    if (pID) {
        query.pID = pID
    }
    phone = phone || ''
    let rank, count
    if (type == 0) {
        if (pID != null) {
            let pDoc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
            if (pDoc) {
                let { rank, value } = rankHandle.getPowerRankByPID(serverID, pID, phone)
                let sData = {
                    id: pDoc.id,
                    pID: pDoc._id.toString(),
                    name: pDoc.name,
                    rank: rank + 1,
                    value: value,
                }
                rank = [sData]
                count = 1
            }
        } else {
            let docs = rankHandle.getPowerRank(serverID, phone)
            count = docs.length
            rank = docs.slice((page - 1) * pageSize, page * pageSize)
        }
        return {
            err: 0, data: {
                data: rank,
                total: count,
            }
        }
    } else if (type == 1) {
        if (pID != null) {
            let pDoc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
            if (pDoc) {
                let { rank, value } = rankHandle.getArenaRankByPID(serverID, pID, phone)
                let sData = {
                    id: pDoc.id,
                    pID: pDoc._id.toString(),
                    name: pDoc.name,
                    rank: rank + 1,
                    value: value,
                }
                rank = [sData]
                count = 1
            }
        } else {
            let docs = rankHandle.getArenaRank(serverID, phone)
            count = docs.length
            rank = docs.slice((page - 1) * pageSize, page * pageSize)
        }
        return {
            err: 0, data: {
                data: rank,
                total: count,
            }
        }
    } else if (type == 2) {
        if (pID != null) {
            let pDoc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
            if (pDoc) {
                let { rank, value } = rankHandle.getMapProgressRankByPID(serverID, pID, phone)
                let sData = {
                    id: pDoc.id,
                    pID: pDoc._id.toString(),
                    name: pDoc.name,
                    rank: rank + 1,
                    value: value,
                }
                rank = [sData]
                count = 1
            }
        } else {
            let docs = rankHandle.getMapProgressRank(serverID, phone)
            count = docs.length
            rank = docs.slice((page - 1) * pageSize, page * pageSize)
        }
        return {
            err: 0, data: {
                data: rank,
                total: count,
            }
        }
    } else if (type == 3) {
        if (pID != null) {
            let pDoc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
            if (pDoc) {
                let { rank, value } = rankHandle.getAbyssProgressRankByPID(serverID, pID, phone)
                let sData = {
                    id: pDoc.id,
                    pID: pDoc._id.toString(),
                    name: pDoc.name,
                    rank: rank + 1,
                    value: value,
                }
                rank = [sData]
                count = 1
            }
        } else {
            let docs = rankHandle.getAbyssProgressRank(serverID, phone)
            count = docs.length
            rank = docs.slice((page - 1) * pageSize, page * pageSize)
        }
        return {
            err: 0, data: {
                data: rank,
                total: count,
            }
        }
    } else {
        return {
            err: 1
        }
    }
})

routes.setLogin('getMyRank', [
], async (msg, session) => {
    let { pID, serverID, phone } = session
    let powerRank = rankHandle.getPowerRankByPID(serverID, pID, phone)
    let arenaRank = rankHandle.getArenaRankByPID(serverID, pID, phone)
    let mapProgressRank = await rankHandle.getMapProgressRankByPID(serverID, pID, phone)
    let abyssRank = await rankHandle.getAbyssProgressRankByPID(serverID, pID, phone)
    return {
        err: 0, data: {
            powerRank,
            arenaRank,
            mapProgressRank,
            abyssRank,
        }
    }
})

routes.setLogin('setArenaFormation', [
    ['team', 'any']
], async (msg, session) => {
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
    if (doc) {
        await mongodbHandle.playerDao.updateOne({ _id: ObjectId(session.pID) }, { $set: { arenaTeam: msg.team, arenaTeamTime: moment().valueOf() } })
    }
    return { err: 0 }
})



routes.setLogin('getAreaCsData', [], async (msg, session) => {
    let areaCsData = await areaCsHandle.getAreaCsData()
    return {
        err: 0, data: {
            areaCsData: areaCsData
        }
    }
})

routes.setLogin('getPerAreaCsData', [], async (msg, session) => {
    let areaCsData = await areaCsHandle.getPreAreaCsData()
    return {
        err: 0, data: {
            areaCsData: areaCsData
        }
    }
})

routes.setLogin('getAreaCsList', [], async (msg, session, cb) => {
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })

    let docs1 = await mongodbHandle.areaCsDao.findByPageAndSort({
        pID1: session.pID
    }, {
        'time': -1
    }, 0, 20)
    let docs2 = await mongodbHandle.areaCsDao.findByPageAndSort({
        pID2: session.pID
    }, {
        'time': -1
    }, 0, 20)
    let docs = docs1.concat(docs2)
    docs.sort((a1, a2) => {
        return a2.time - a1.time
    })
    docs = docs.slice(0, 20)
    docs.forEach(item => {

        delete item.player1
        delete item.player2
    })

    let areaCsTimes = myData.areaCsTimes
    if (myData.areaCsTime !== moment().startOf('day').valueOf()) {
        areaCsTimes = 0
    }

    let pID = session.pID
    let areaCsData = await areaCsHandle.getAreaCsData()
    let areaCsConfig = gameConfigHandle.gameConfig.areaCs

    let playerCount = 0
    for (let id = 1; id <= areaCsConfig.areaCsAmount; id++) {

        let territory = areaCsData.areaCsList[id];
        if (!territory) continue; // 跳过无主领地
        if (!territory || !territory.sID) continue; // 跳过无主领地

        if (pID == territory.pID) {
            playerCount++;
        }
    }


    return {
        err: 0, data: {
            arenaData: docs,
            areaCsTimes: areaCsTimes,
            playerCount: playerCount,
            areaCsData: areaCsData
        }
    }

})


routes.setLogin('getAreaCsIndexData', [
    ['cID', 'number'],
], async (msg, session) => {
    let { cID } = msg

    let areaCsData = await areaCsHandle.getAreaCsData()
    let areaCsItemData = areaCsData.areaCsList[cID]
    await areaCsHandle.saveAreaCsData(areaCsData)
    return { err: 0, data: { areaCsItemData: areaCsItemData } }
})
routes.setLogin('saveBattleAreaCsData', [
    ['name1', 'string'],
    ['name2', 'string'],
    ['result', 'number'],
    ['version', 'string'],
    ['seed', 'number'],
    ['cID', 'number'],
], async (msg, session, cb) => {
    let { name1, name2, result, version, seed, cID } = msg
    let areaCsData = await areaCsHandle.getAreaCsData()
    let pID = session.pID
    let pID2 = areaCsData.areaCsList[cID].pID
    let player1 = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    let player2 = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID2) })
    await mongodbHandle.areaCsDao.newAndSave(name1, name2, session.pID, pID2,
        player1.currentServerID, player2.currentServerID, result, seed, version, cID)

    return { err: 0 }
})


routes.setLogin('saveAreaCsDataRoute', [
    ['cID', 'number'],
], async (msg, session) => {
    let { cID } = msg
    let pID = session.pID
    let time = moment().valueOf()
    let areaCsData = await areaCsHandle.getAreaCsData()
    if (areaCsData.areaCsList[cID].bID != pID) {
        return { err: 2 }
    }
    if (time - areaCsData.areaCsList[cID].t > 5 * 60 * 1000) {
        return { err: 3 }
    }
    areaCsData.areaCsList[cID].pID = pID
    areaCsData.areaCsList[cID].sID = session.serverID
    areaCsData.areaCsList[cID].bID = null
    await areaCsHandle.saveAreaCsData(areaCsData)
    return { err: 0 }
})


routes.setLogin('addAreaCsTimes', [
    ['cID', 'number'],
], async (msg, session, cb) => {
    let { cID } = msg
    let time = moment().valueOf()

    let areaCsConfig = gameConfigHandle.gameConfig.areaCs
    const areaCsTimeFig = areaCsConfig.areaCsTime

    let date = new Date(time);
    // 转换为分钟总数便于比较
    const currentTime = date.getHours() * 100 + date.getMinutes();
    // 时间段判断
    let tipStatus = 0;
    if (currentTime >= areaCsTimeFig.nStart && currentTime < areaCsTimeFig.nEnd) {
        tipStatus = 2; // 20:00-22:00
    }
    if (tipStatus == 0) {
        return { err: 3 }
    }

    let player1 = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
    let areaCsTimes = player1.areaCsTimes
    let areaCsTime = player1.areaCsTime

    if (player1.areaCsTime !== moment().startOf('day').valueOf() || !areaCsTime) {
        areaCsTimes = 0
        areaCsTime = moment().startOf('day').valueOf()
    }
    let isVip = false
    let vipTime = (player1.vipTime || new Date().getTime())
    if (vipTime > moment().valueOf()) {
        isVip = true
    }
    if (areaCsTimes >= areaCsPlayHandle.getAreaCsTimes(player1.playerData, null, null)) {
        return { err: 1 }
    }
    let areaCsData = await areaCsHandle.getAreaCsData()

    if (areaCsData.areaCsList[cID].t && areaCsData.areaCsList[cID].t > 0) {
        if ((time - areaCsData.areaCsList[cID].t) < 5 * 60 * 1000) {
            return { err: 2 }
        }
    }

    areaCsData.areaCsList[cID].t = time
    areaCsData.areaCsList[cID].bID = session.pID
    await areaCsHandle.saveAreaCsData(areaCsData)

    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(session.pID),
    }, {
        $set: {
            areaCsTimes: areaCsTimes + 1,
            areaCsTime: areaCsTime
        }
    })
    let player2
    let playerCount = 0, oppentCount = 0
    let oppentPID = areaCsData.areaCsList[cID].pID
    if (oppentPID) {
        player2 = await mongodbHandle.playerDao.findOne({ _id: ObjectId(oppentPID) })
        delete player2.playerData.bag
        delete player2.playerData.equipmentBag
        delete player2.playerData.abyssBag
        delete player2.playerData.petBag
        delete player2.playerData.abyssBag
        delete player2.playerData.rideBag
        delete player2.playerData.itemInfo
        delete player2.playerData.useInfo
        delete player2.playerData.technologies
        delete player2.playerData.worldBossMarket
        delete player2.playerData.mysteryMarket
        delete player2.playerData.armyMarket
        delete player2.playerData.adventure

        for (let id = 1; id <= areaCsConfig.areaCsAmount; id++) {
            let territory = areaCsData.areaCsList[id];
            if (!territory) continue; // 跳过无主领地  
            if (session.pID == territory.pID) {
                playerCount++;
            } else if (oppentPID && oppentPID == territory.pID) {
                oppentCount++;
            }
        }

    }


    return { err: 0, data: { oppentData: player2, playerCount, oppentCount } }


})


routes.setLogin('getOpponentCs', [
    ['pID', 'string'],
], async (msg, session) => {
    let { pID } = msg

    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    delete doc.playerData.Bag
    delete doc.playerData.EquipmentBag
    delete doc.playerData.AbyssBag
    delete doc.playerData.PetBag
    delete doc.playerData.AbyssBag
    delete doc.playerData.RideBag
    delete doc.playerData.ItemInfo

    let areaCsData = await areaCsHandle.getAreaCsData()
    let areaCsConfig = gameConfigHandle.gameConfig.areaCs

    let playerCount = 0
    for (let id = 1; id <= areaCsConfig.areaCsAmount; id++) {
        let territory = areaCsData.areaCsList[id];
        if (!territory || !territory.sID) continue; // 跳过无主领地  
        if (pID == territory.pID) {
            playerCount++;
        }
    }

    return { err: 0, data: { doc: doc, playerCount: playerCount } }
})


routes.setLogin('cancelAreaCs', [
    ['cID', 'number'],
], async (msg, session) => {
    let { cID, type } = msg
    let pID = session.pID
    let time = moment().valueOf()
    let areaCsData = await areaCsHandle.getAreaCsData()
    if (areaCsData.areaCsList[cID].pID == pID) {
        areaCsData.areaCsList[cID].pID = null
        areaCsData.areaCsList[cID].bID = null
        areaCsData.areaCsList[cID].t = 0
        areaCsData.areaCsList[cID].sID = 0
    } else {
        return { err: 1 }
    }
    await areaCsHandle.saveAreaCsData(areaCsData)
    return { err: 0 }
})

routes.setLogin('getPerAreaCsCount', [], async (msg, session) => {
    let pID = session.pID
    let areaCsData = await areaCsHandle.getPreAreaCsData()
    let areaCsConfig = gameConfigHandle.gameConfig.areaCs

    let playerCount = 0
    let ids = []
    if (areaCsData) {
        if (areaCsData.areaCsList) {
            for (let id = 1; id <= areaCsConfig.areaCsAmount; id++) {

                if (!areaCsData.areaCsList[id]) continue; // 跳过无主领地  
                let territory = areaCsData.areaCsList[id];
                if (!territory) continue; // 跳过无主领地
                if (!territory || !territory.sID) continue; // 跳过无主领地

                if (pID == territory.pID) {
                    playerCount++;
                    ids.push(id);
                }
                // // 记录该区最新的领地占领时间
                // if (territory.t > areaCsCount[serverZone].latestTime) {
                //     areaCsCount[serverZone].latestTime = territory.t;
                // }
            }
        }
    }

    let playerStats: Record<string, { count: number; sID: number; territoryIds: number[] }> = {};
    const rank: { range: number; pID: string; name: string; count: number; sID: number }[] = [];

    // 预先为所有6个区间创建默认值
    for (let rangeNum = 1; rangeNum <= areaCsConfig.areaCsNum; rangeNum++) {
        rank.push({
            range: rangeNum,
            pID: "----",
            name: "无人占领",
            count: 0,
            sID: 0
        });
    }

    if (areaCsData) {
        if (areaCsData.areaCsList) {
            const rangeStats: Record<number, Record<string, number>> = {};
            for (let rangeNum = 1; rangeNum <= areaCsConfig.areaCsNum; rangeNum++) {
                rangeStats[rangeNum] = {};
            }

            for (let id = 1; id <= areaCsConfig.areaCsAmount; id++) {
                let territory = areaCsData.areaCsList[id];
                if (!territory) continue;
                if (!territory?.sID) continue;

                let playerID = territory.pID;
                if (!playerID) continue;

                // 更新玩家总统计
                if (!playerStats[playerID]) {
                    playerStats[playerID] = {
                        count: 0,
                        sID: 0,
                        territoryIds: []
                    };
                }
                playerStats[playerID].count++;
                playerStats[playerID].sID = territory.sID;
                playerStats[playerID].territoryIds.push(id);

                // 更新区间统计
                const rangeNum = Math.ceil(id / 100);

                if (!rangeStats[rangeNum][playerID]) {
                    rangeStats[rangeNum][playerID] = 0;
                }
                rangeStats[rangeNum][playerID]++;
            }

            // 更新每个区间的占领者信息
            for (const [rangeStr, stats] of Object.entries(rangeStats)) {
                const rangeNum = parseInt(rangeStr);
                let maxCount = 0;
                let topPlayerID = "";
                let topSID = 0;

                for (const [playerID, count] of Object.entries(stats)) {
                    if (count > maxCount) {
                        maxCount = count;
                        topPlayerID = playerID;
                        topSID = playerStats[topPlayerID]?.sID || 0;
                    }
                }

                if (topPlayerID !== "") {
                    try {
                        const player = await mongodbHandle.playerDao.findOne({
                            _id: new ObjectId(topPlayerID)
                        });

                        // 更新对应区间的信息
                        const index = rangeNum - 1; // 因为rangeNum从1开始
                        rank[index] = {
                            range: rangeNum,
                            pID: topPlayerID,
                            name: player?.name || ('未知玩家' + topPlayerID.slice(-4)),
                            count: maxCount,
                            sID: topSID
                        };
                    } catch (e) {
                        const index = rangeNum - 1;
                        rank[index] = {
                            range: rangeNum,
                            pID: topPlayerID,
                            name: '----',
                            count: maxCount,
                            sID: topSID
                        };
                    }
                }
            }
        }
    }

    return { err: 0, data: { playerCount: playerCount, rank: rank, ids: ids } }
})